package com.zzh.htts.voice;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.zzh.lib.htts.HTTSLib;
import com.zzh.lib.htts.callback.OnSetParamsCallback;
import com.zzh.lib.htts.callback.OnUtteranceProgressListener;
import com.zzh.lib.htts.params.HTTSParams;
import com.zzh.lib.recorder.HMediaRecorderParams;
import com.zzh.lib.recorder.def.IRecorder;
import com.zzh.lib.recorder.def.OnRecorderProcessListener;
import com.zzh.lib.recorder.pcm.PCMRecorder;
import com.zzh.lib.recorder.ui.RecorderActivity;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.function.LongUnaryOperator;

/**
 * @Date: 5/10/21 8:53 AM
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: MainActivity.java 语音合成
 */
public class MainActivity extends Activity {

    private EditText et;
    IRecorder pcmRecorder;
    HVoiceWave vw;
    String[] jys = {"静夜思", "床前明月光", "疑是地上霜", "举头望明月", "低头思故乡"};
    String[] yc = {"宣州谢朓楼饯别校书叔云", "弃我去者", "昨日之日不可留", "乱我心者", "今日之日多烦忧", "长风万里送秋雁", "对此可以酣高楼",
            "蓬莱文章建安骨", "中间小谢又清发", "俱怀逸兴壮思飞", "欲上青天览明月", "抽刀断水水更流", "举杯消愁愁更愁", "人生在世不称意", "明朝散发弄扁舟"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HTTSLib.getInstance().registerApplication(this.getApplication());
        et = findViewById(R.id.et);
        vw = findViewById(R.id.vw);
        findViewById(R.id.btn_pcm_list).setOnClickListener(v -> startActivity(new Intent(MainActivity.this, PcmListActivity.class)));

        findViewById(R.id.btn_demo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permission = checkSelfPermission(Manifest.permission.CAMERA);
                if (permission == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(MainActivity.this, DemoActivity.class);
                    startActivityForResult(intent, 1000);
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 1000);
                }
            }
        });
        findViewById(R.id.btn_video).setOnClickListener(v -> {
            int permission = checkSelfPermission(Manifest.permission.CAMERA);
            if (permission == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(MainActivity.this, RecorderActivity.class);
                startActivityForResult(intent, 1000);
            } else {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1000);
            }
        });
        pcmRecorder = initPCMRecorder();
        findViewById(R.id.btn_pcm_pause).setOnClickListener(v -> {
            if (pcmRecorder != null) {
                pcmRecorder.pause();
            }
        });
        findViewById(R.id.btn_pcm_resume).setOnClickListener(v -> {
            if (pcmRecorder != null) {
                pcmRecorder.resume();
            }
        });
        findViewById(R.id.btn_pcm_demo).setOnClickListener(v -> {

            int permission = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
            if (permission == PackageManager.PERMISSION_GRANTED) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(MainActivity.this, RecordService.class));
                } else {
                    startService(new Intent(MainActivity.this, RecordService.class));
                }
            } else {
                requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1000);
            }
        });
        findViewById(R.id.btn_pcm_stop).setOnClickListener(v -> {
            Intent service = new Intent(MainActivity.this, RecordService.class);
            service.putExtra("RECORD_TYPE", "release");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(service);
            } else {
                startService(service);
            }
        });

        TtsTaskQueue.INSTANCE.registerListener(new TtsQueueListener() {
            @Override
            public void onEnd() {
                Log.e("TTS", "tts 结束");
            }
        });


        findViewById(R.id.btn_add_jys).setOnClickListener(v -> {

            for (String text : jys) {
                TtsTaskQueue.INSTANCE.addString(text);

            }
            TtsTaskQueue.INSTANCE.addString("end");

        });
        findViewById(R.id.btn_add_yc).setOnClickListener(v -> {

            for (String text : yc) {
                TtsTaskQueue.INSTANCE.addString(text);

            }
            TtsTaskQueue.INSTANCE.addString("end");
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    long dot = System.currentTimeMillis();

    private IRecorder initPCMRecorder() {
        HMediaRecorderParams params = new HMediaRecorderParams();
        params.setAudioEncoder(4000);
        params.setSave2File(true);
        params.setDenoise(true);
        params.setFileSaveDir(getCacheDir().getAbsolutePath());
        params.setOnRecorderProcessListener(new OnRecorderProcessListener() {
            @Override
            public void onBeforeInitAudioRecord(IRecorder recorder) {

            }

            @Override
            public void onProcess(PCMRecorder recorder, byte[] buffer, int len) {
                Log.d("--pcm", "pcm 音频：" + Arrays.toString(buffer));
                Log.d("--pcm", "pcm len：" + len);
            }

            @Override
            public void volumeChange(double volume) {

                if ((System.currentTimeMillis() - dot) > 300) {
                    int voiceSize = (int) (volume * 6);
                    Log.d("--pcm", "pcm 音量：" + voiceSize);
                    vw.addVoiceSize(voiceSize);
                    dot = System.currentTimeMillis();

                }

            }

            @Override
            public void onStart(PCMRecorder recorder) {

                Log.d("--pcm", "pcm 开始录制: " + recorder.getRecordFile().getAbsolutePath());
            }

            @Override
            public void onEnd(long duration) {
                Log.d("--pcm", "pcm 录制结束: " + duration);

            }
        });

        return HTTSLib.getInstance().setRecorderParams(params).create();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Set<String> keySet = extras.keySet();
                Iterator<String> iterator = keySet.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    Log.d("----", "-------数据：" + String.valueOf(extras.get(next)));
                }
            }
        }
    }

    public void onClickView(View view) {
        CharSequence text = et.getText().toString();
        if (HTTSLib.getInstance() != null) {
            OnUtteranceProgressListener onUtteranceProgressListener = new OnUtteranceProgressListener() {
                @Override
                public void onStart(String utteranceId) {
                    super.onStart(utteranceId);
                    Log.d("----tts: ", "onStart: " + utteranceId);
                }

                @Override
                public void onDone(String utteranceId) {
                    super.onDone(utteranceId);
                    Log.d("----tts: ", "onDone: " + utteranceId);
                }

                @Override
                public void onError(String utteranceId) {
                    super.onError(utteranceId);
                    Log.d("----tts: ", "onError: " + utteranceId);
                }

                @Override
                public void onError(String utteranceId, int errorCode) {
                    super.onError(utteranceId, errorCode);
                    Log.d("----tts: ", "onError: " + utteranceId + ", " + errorCode);
                }

                @Override
                public void onStop(String utteranceId, boolean interrupted) {
                    super.onStop(utteranceId, interrupted);
                    Log.d("----tts: ", "onStop: " + utteranceId);
                }

                @Override
                public void onBeginSynthesis(String utteranceId, int sampleRateInHz, int audioFormat, int channelCount) {
                    super.onBeginSynthesis(utteranceId, sampleRateInHz, audioFormat, channelCount);
                    Log.d("----tts: ", "onBeginSynthesis: " + utteranceId);
                }

                @Override
                public void onAudioAvailable(String utteranceId, byte[] audio) {
                    super.onAudioAvailable(utteranceId, audio);
                    Log.d("----tts: ", "onAudioAvailable: " + utteranceId);
                }

                @Override
                public void onRangeStart(String utteranceId, int start, int end, int frame) {
                    super.onRangeStart(utteranceId, start, end, frame);
                    Log.d("----tts: ", "onRangeStart: " + utteranceId);
                }
            };
            HTTSLib httsLib = HTTSLib.getInstance().setParams(new HTTSParams(2f));
            int speak = httsLib.speak(text, onUtteranceProgressListener);
            Log.d("----", "-------播放设置：" + speak);
        } else {
            Toast.makeText(MainActivity.this, "请先点击初始化按钮", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HTTSLib.getInstance().release();
    }

    public void onClickViewServer(View view) {
        HTTSLib.getInstance().init(this.getApplicationContext(), status -> {
            Log.d("---", String.valueOf(status));
            if (status == TextToSpeech.SUCCESS) {
                Toast.makeText(MainActivity.this, "初始化成功: " + status, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "初始化失败: " + status, Toast.LENGTH_SHORT).show();
            }
        }).setCallback(new OnSetParamsCallback() {
            @Override
            public void onSetLanguage(int language) {
                Log.d("---", "设置当前语言是否成功code: " + String.valueOf(language));
            }
        });
    }

    String[] text = {"床", "前", "明", "月", "光", "，", "疑", "是", "地", "上", "霜", "。", "举", "头", "望", "明", "月", "，", "低", "头", "思", "故", "乡", "。", "这是", "李", "白", "的静", "夜思", "小", "学时", "学", "到的", "非", "常优", "美", "的文", "字", "。"};


    public void onClickViewContinue(View view) {
        for (String t : text) {
            HTTSLib.getInstance().speak(t, TextToSpeech.QUEUE_ADD);
        }
    }

    public void onClickViewDown(View view) {
        HTTSLib.getInstance().release();
    }
}